#! /bin/bash
CLUSTER_NAME=${1:-cds_etcd}
# default cluster size is 3
CLUSTER_SIZE=${2:-3}
# create cluster by discovery service provided by etcd.io
#DISCOVERY_URL=`curl https://discovery.etcd.io/new?size=$CLUSTER_SIZE`
# curl to keep etcd url alive
#curl $DISCOVERY_URL
HOST_IP=$(ip addr show eth0 | grep "inet " | awk '{ split($2, a, "/", seps); print a[1]}')
CLUSTER=""
for i in $(seq 1 $CLUSTER_SIZE);do
    CLUSTER="$CLUSTER${CLUSTER_NAME}_$i=http://$HOST_IP:$[7000+$i],"
    # configure firewall to allow client and peer communication
    iptables -L IN_public_allow -n  | grep "tcp dpt:$[4000+$i]" > /dev/null || {
        echo "allow $[4000+$i] port for client access"
        firewall-cmd --permanent --add-port=$[4000+$i]/tcp # client access
        iptables -A IN_public_allow -m conntrack --ctstate NEW -m tcp -p tcp --dport $[4000+$i] -j ACCEPT
    }
    iptables -L IN_public_allow -n | grep "tcp dpt:$[7000+$i]" > /dev/null || {
        echo "allow $[7000+$i] port for peer access"
        firewall-cmd --permanent --add-port=$[7000+$i]/tcp # peer access
        iptables -A IN_public_allow -m conntrack --ctstate NEW -m tcp -p tcp --dport $[7000+$i] -j ACCEPT
    }
done
# avoid reload firewall, otherwize docker will throw errors when starting new container and add iptable rules
#[ -n "${FW_CHANGE+true}" ] && {
#    echo "reload firewall to make new rules take affect"
#    firewall-cmd --reload
#    sleep 10  # sleep 10 seconds to allow network come back
#}

CLUSTER=${CLUSTER::-1}
echo "cluster info:$CLUSTER"

BASE_DOCKER_DIR=/data/docker/$CLUSTER_NAME
[ -d $BASE_DOCKER_DIR ] && rm -fr $BASE_DOCKER_DIR
mkdir -p $BASE_DOCKER_DIR
for i in $(seq 1 $CLUSTER_SIZE);do
    mkdir $BASE_DOCKER_DIR/$i
    docker run -d -p $[4001-1+$i]:4001 -p $[7001-1+$i]:7001 -v $BASE_DOCKER_DIR/$i:/data \
        --name ${CLUSTER_NAME}_$i cds/etcd:latest  -name ${CLUSTER_NAME}_$i \
        -advertise-client-urls http://$HOST_IP:$[4000+$i] \
        -initial-advertise-peer-urls http://$HOST_IP:$[7000+$i] \
        -initial-cluster-token $CLUSTER_NAME \
        -initial-cluster $CLUSTER \
        -initial-cluster-state new
        #-discovery $DISCOVERY_URL \
done
